/**
 * @author:albert
 */

package com.bkbw.live.battle.net.server;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.bkbw.live.battle.net.message.MessageCenter;
import com.bkbw.live.battle.net.message.MessageObject;
import com.bkbw.live.common.dataproto.ClientToBattleServerPb;
import com.bkbw.live.common.dataproto.ClientToBattleServerPb.HeadType;
import com.bkbw.live.common.dataproto.ClientToBattleServerPb.LoginReq;
import com.bkbw.live.common.dataproto.ClientToBattleServerPb.Logout;

public class BattleServerHandler extends IoHandlerAdapter
{
	static AtomicInteger count = new AtomicInteger();
	static Map<IoSession,Integer> sessionMap = new HashMap<IoSession,Integer>();
    @Override
	public void sessionCreated(IoSession session) throws Exception {
		super.sessionCreated(session);
		count.incrementAndGet();
		System.out.println("session create:"+count);
	}
	@Override
	public void sessionClosed(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		super.sessionClosed(session);
		count.decrementAndGet();
		System.out.println("客户端"+sessionMap.get(session)+"正常离开了");
		System.out.println("session close:"+count);
		closeSession(session);
	}
	@Override
    public void exceptionCaught( IoSession session, Throwable cause ) throws Exception
    {
    		System.out.println("客户端"+sessionMap.get(session)+"异常离开了");
    		cause.printStackTrace();
    		closeSession(session);
    }
    @Override
    public void messageReceived( IoSession session, Object message ) throws Exception
    {
    		MessageObject mo = (MessageObject) message;
    		//保存玩家session和id，以便当玩家非正常退出时，关闭连接
    		if(mo.getHead()==HeadType.DUNGON_LOGIN_REQ_VALUE){
    			ClientToBattleServerPb.LoginReq req = (LoginReq) mo.getData();
    			//先踢出，再登入
    			if(sessionMap.containsKey(session)){
    				closeSession(session);
    			}
    			sessionMap.put(session, req.getUserId());
    		}
    		//玩家退出时，等同掉线处理
    		if(mo.getHead()==HeadType.DUNGON_LOGOUT_VALUE){
    			closeSession(session);
    			return;
    		}
    		//交给消息分发中心去处理
    		MessageCenter.getInstance().dispacthMessage(mo);
    }
    @Override
    public void sessionIdle( IoSession session, IdleStatus status ) throws Exception
    {
        //System.out.println( "IDLE " + session.getIdleCount( status ));
    }
    
    private void closeSession(IoSession session){
    		if(sessionMap.containsKey(session)){
			int id = sessionMap.get(session);
			Logout.Builder logoutBuilder = Logout.newBuilder();
			logoutBuilder.setUserId(id);
			//广播出去
			MessageObject mo = new MessageObject(HeadType.DUNGON_LOGOUT_VALUE, logoutBuilder.build(), session);
			MessageCenter.getInstance().dispacthMessage(mo);
			sessionMap.remove(session);
		}
    }
}
